package com.gjy.service.uuid.config;

import com.gjy.service.uuid.event.UuidEvent;
import com.gjy.service.uuid.event.UuidEventFactory;
import com.gjy.service.uuid.event.UuidEventHandler;
import com.lmax.disruptor.BlockingWaitStrategy;
import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.dsl.Disruptor;
import com.lmax.disruptor.dsl.ProducerType;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;

/**
 * @author gjy
 * @version 1.0
 * @since 2025-10-12 10:20:28
 */
@Configuration
public class DisruptorConfig {

    @Resource
    private UuidEventHandler uuidEventHandler;

    /**
     * 创建Disruptor实例
     */
    @Bean
    public Disruptor<UuidEvent> disruptor() {
        // 创建线程工厂
        ThreadFactory threadFactory = Executors.defaultThreadFactory();

        // 创建Disruptor
        Disruptor<UuidEvent> disruptor = new Disruptor<>(
                new UuidEventFactory(),
                1024, // 环形缓冲区大小，必须是2的幂
                threadFactory,
                ProducerType.MULTI, // 多生产者模式
                new BlockingWaitStrategy() // 等待策略
        );

        // 设置事件处理器
        disruptor.handleEventsWith(uuidEventHandler);

        // 启动Disruptor
        disruptor.start();

        return disruptor;
    }

    /**
     * 创建RingBuffer
     */
    @Bean
    public RingBuffer<UuidEvent> ringBuffer(Disruptor<UuidEvent> disruptor) {
        return disruptor.getRingBuffer();
    }
}
